package com.ml.mall.service.variant.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ml.mall.entity.variant.SysProductVariantSku;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.variant.SysProductVariantSkuMapper;
import com.ml.mall.service.variant.SysProductVariantSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;

/**
* <p>
    *  服务实现类
    * </p>
*
* @author kyyang
* Created 2021-05-18
*/
@Service
public class SysProductVariantSkuServiceImpl extends ServiceImpl<SysProductVariantSkuMapper, SysProductVariantSku> implements SysProductVariantSkuService {

    @Autowired
    private  SysProductVariantSkuMapper  sysProductVariantSkuMapper;


    @Override
    public SysProductVariantSku getSkuByVariantId(Long variantId) {
        //查询 sku 详情
        QueryWrapper<SysProductVariantSku> w2 = new QueryWrapper<>();
        w2.eq("variant_id", variantId);
        SysProductVariantSku sysProductVariantSku = this.getOne(w2);
        return sysProductVariantSku;
    }

    @Override
    public void changeInventory(Long variantId, Integer quantity) {
        //查询 sku 属性
        QueryWrapper<SysProductVariantSku> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("variant_id", variantId);
        SysProductVariantSku one1 = this.getOne(queryWrapper);
        //减库存
        if (one1.getStock() == null || one1.getStock().intValue() <= 0) {
            throw new BizException(CommonEnum.SKUDATA_STOCK_ERROR);
        }
        BigDecimal Stock = BigDecimal.valueOf(one1.getStock()).subtract(BigDecimal.valueOf(quantity));
        if (Stock.compareTo(BigDecimal.ZERO) < 0) {
            throw new BizException(CommonEnum.SKUDATA_STOCK_ERROR);
        }
        one1.setStock(Stock.intValue());
        this.updateById(one1);
    }
}
